import React, { useState, useRef, useEffect } from 'react';
import { Modal, Card, Tabs, Form, Checkbox, Input, Button, Space, Row, Col, Tooltip, DatePicker, Select, TimePicker, InputNumber } from 'antd';
import FormCondition from '@/components/FormCondition';
import { dateDisabled } from '@/common/regular';
import { qaType_status } from '@/common/contact'
import { PlusOutlined, MinusCircleOutlined, QuestionCircleOutlined } from '@ant-design/icons'
import { connect, } from 'umi';
import moment from 'moment';
const { RangePicker } = DatePicker;
const SelectScroll = (props) => {
    const { dispatch, xqList, restField, name, form, teacherScheduleList = [] } = props
    const [roomList, setRoomList] = useState([])
    const [campusId, setCampusId] = useState(null)

    useEffect(() => {
        if (campusId) {
            dispatch({
                type: 'answering/fetchListCampusClassroom',
                payload: {
                    campusId: campusId
                },
                callback: (e) => {
                    setRoomList(e)
                }
            })
        }
    }, [campusId])
    useEffect(() => {
        console.log(name, 'name,初始化', teacherScheduleList)
        teacherScheduleList.forEach((item, index,) => {
            if (index === name && item.campusId) {
                setCampusId(item.campusId)
            }
        })
    }, [])
    return <>
        <Col style={{ paddingLeft: 80 }} span={24}>
            <Form.Item
                {...restField}
                name={[name, 'campusId']}
                required
                label={'选择校区'}
                rules={[
                    {
                        required: true,
                        message: '请选择校区',
                    },
                ]}
            >
                <Select onChange={(e, option) => {
                    const {
                        provinceName,
                        cityName,
                        districtName,
                        address
                    } = option
                    if (e !== campusId) {
                        setCampusId(e)
                        const list = form.getFieldValue('teacherScheduleList')
                        form.setFieldsValue({
                            teacherScheduleList: list.map((item, index) => {
                                if (index === name) {
                                    return {
                                        ...item,
                                        classroomId: null,
                                        fullAddress: provinceName + cityName + districtName + address,
                                        campusId: e,
                                    }
                                }
                                return item
                            })
                        })
                    }

                }} fieldNames={{
                    label: 'campusName', value: 'id',
                }} options={xqList}></Select>
            </Form.Item>
        </Col>
        {campusId && <Col style={{ paddingLeft: 80 }} span={24}>
            <Form.Item
                {...restField}
                name={[name, 'classroomId']}
                required
                label={'选择班级'}
                rules={false}
            >
                <Select
                    onChange={(e, option) => {
                        const list = form.getFieldValue('teacherScheduleList')
                        form.setFieldsValue({
                            teacherScheduleList: list.map((item, index) => {
                                if (index === name) {
                                    return {
                                        ...item,
                                        classroomId: e,

                                    }
                                }
                                return item
                            })
                        })

                    }}
                    fieldNames={{
                        label: 'classroomName', value: 'id',
                    }}
                    options={roomList}
                ></Select>
            </Form.Item>
        </Col>}
        <Col style={{ paddingLeft: 80 }} span={24}>
            <Form.Item
                {...restField}
                label={'详细地址'}
                name={[name, 'fullAddress']}
                required
                rules={false}
            >
                <Input disabled={true}></Input>
            </Form.Item>
        </Col>
    </>
}
const generateDateArray = (startDate, endDate) => {
    if (
        !startDate || !endDate
    ) {
        return []
    }
    const dates = [];
    let currentDate = moment(startDate);
    const finalDate = moment(endDate);

    // 循环生成日期
    while (currentDate.isSameOrBefore(finalDate)) {
        dates.push(currentDate.format('YYYY-MM-DD'));
        currentDate = currentDate.add(1, 'days');
    }

    return dates;
};
const SelectDate = (props) => {
    const { form, name, nameChange, restField, teacherScheduleList } = props
    const [option, setOption] = useState([])
    const selectList = (name) => {
        let datas = form.getFieldValue('teacherScheduleList').reduce((item, val, index) => {
            if (index === name) {
                return {
                    ...val
                }
            }
            return item
        }, {})
        const { dateTime = [] } = datas
        const [startTime, endTime] = dateTime
        setOption(generateDateArray(startTime, endTime).map((val, index) => {
            return {
                label: val,
                value: val
            }
        }))
    }
    useEffect(() => {
        if (nameChange === name) {
            selectList(nameChange)
        }
    }, [nameChange])
    useEffect(() => {
        teacherScheduleList.forEach((item, index,) => {
            const { dateTime = [] } = item
            const [startTime, endTime] = dateTime
            if (index === name && startTime && endTime) {
                selectList(name)
            }
        })
    }, [])
    return <Form.Item
        {...restField}
        name={[name, 'excludeDates']}
        label='休息日'
        rules={false}
    >

        <Select mode='tags' options={option}></Select>
    </Form.Item>
}
const WeekItem = (props) => {
    const { defaultScheduleList = [], dispatch, xqList, form, teacherScheduleList } = props
    const weelList = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    const [nameChange, setNameChange] = useState(null)
    console.log(nameChange, 'nameChange')
    return <Row gutter={[24, 24]}>
        <Col span={24}>
            <Form.List name={'teacherScheduleList'}>
                {(fields, { add, remove }) => (
                    <>
                        {fields.map(({ key, name, ...restField }) => (
                            <Space
                                key={key}
                                direction={'vertical'}
                                style={{
                                    display: 'flex',
                                    marginBottom: 8,
                                }}
                            >
                                <div style={{ position: "relative", width: "100%" }}>
                                    <Row>
                                        <Col style={{ position: 'relative' }} span={24}>
                                            <Form.Item
                                                {...restField}
                                                required
                                                label={'答疑周期'}
                                                name={[name, 'dateTime']}
                                                rules={[
                                                    {
                                                        required: true,
                                                        message: '请选择时间',
                                                    },
                                                ]}
                                            >

                                                <RangePicker onChange={(e) => {
                                                    if (e) {
                                                        setNameChange(name)
                                                    }
                                                }} format={'YYYY-MM-DD'} style={{ width: '60%' }} disabledDate={dateDisabled}></RangePicker>
                                            </Form.Item>
                                            <div style={{ position: 'absolute', top: 0, left: 480 }}>
                                                {fields.length > 1 ? (
                                                    <Button type='link' onClick={() => {
                                                        remove(name)
                                                        if (nameChange === name) {
                                                            setNameChange(null)
                                                        }
                                                    }} >删除自定义</Button>
                                                ) : null}
                                            </div>
                                        </Col>
                                        <Col style={{ paddingLeft: 80 }} span={24}>
                                            <Form.Item
                                                {...restField}
                                                name={[name, 'weekDays']}
                                                required
                                            >

                                                <Checkbox.Group options={weelList}></Checkbox.Group>
                                            </Form.Item>
                                        </Col>
                                        <Col style={{ paddingLeft: 80 }} span={24}>
                                            {defaultScheduleList.map((item, keys) => {
                                                const { startTime, endTime, id, scheduleName } = item
                                                return <Space>
                                                    <div style={{ width: 264 }}>
                                                        <Form.Item valuePropName="checked"   {...restField} name={[name, 'schedule' + keys]} >
                                                            <Checkbox>{scheduleName}   {startTime + '-' + endTime}</Checkbox>
                                                        </Form.Item>
                                                    </div>
                                                    <Form.Item  {...restField} label={<div>
                                                        <Tooltip title="当前时间内的学员最大接待人次（如未配置则为详情配置中默认最大接待量）">
                                                            <QuestionCircleOutlined></QuestionCircleOutlined>
                                                        </Tooltip>

                                                        最大学员接待量
                                                    </div>} name={[name, 'scheduleCount' + keys]} >
                                                        <InputNumber style={{ width: 160 }} addonAfter={'位'}></InputNumber>
                                                    </Form.Item>
                                                </Space>
                                            })}
                                        </Col>
                                        <Col style={{ paddingLeft: 80 }} span={24}>
                                            <Form.List name={[name, 'scheduleTimes']}>
                                                {(fieldsInside, { add: addInside, remove: removeInside }) => (
                                                    <>
                                                        {fieldsInside.map((fieldInside) => (
                                                            <Space
                                                                key={fieldInside.key}
                                                                direction={'vertical'}
                                                                style={{
                                                                    display: 'flex',
                                                                    marginBottom: 8,
                                                                }}
                                                            >
                                                                <div style={{ position: "relative", width: "100%" }}>
                                                                    <Row>
                                                                        <Col style={{ position: 'relative' }} span={24}>
                                                                            <Space align={'flex-start'}>
                                                                                <div style={{ width: 264 }}>
                                                                                    <Form.Item
                                                                                        {...fieldInside.restField}
                                                                                        required
                                                                                        name={[fieldInside.name, 'dateTime']}
                                                                                        rules={[
                                                                                            {
                                                                                                required: true,
                                                                                                message: '请选择自定义时间',
                                                                                            },
                                                                                        ]}
                                                                                    >

                                                                                        <TimePicker.RangePicker style={{ width: 240 }} format={'HH:mm'} disabledDate={dateDisabled}></TimePicker.RangePicker>
                                                                                    </Form.Item>
                                                                                </div>


                                                                                <Form.Item
                                                                                    {...fieldInside.restField}
                                                                                    label={<div>
                                                                                        <Tooltip title="当前时间内的学员最大接待人次（如未配置则为详情配置中默认最大接待量）">
                                                                                            <QuestionCircleOutlined></QuestionCircleOutlined>
                                                                                        </Tooltip>

                                                                                        最大学员接待量
                                                                                    </div>}
                                                                                    name={[fieldInside.name, 'maxStudentAmount']}
                                                                                >

                                                                                    <InputNumber style={{ width: 160 }} addonAfter={'位'}></InputNumber>
                                                                                </Form.Item>
                                                                                <div>
                                                                                    {fieldsInside.length > 0 ? (
                                                                                        <Button type='link' onClick={() => removeInside(fieldInside.name)} >删除时间</Button>
                                                                                    ) : null}
                                                                                </div>
                                                                            </Space>
                                                                        </Col>

                                                                    </Row>

                                                                </div>
                                                            </Space>
                                                        ))}
                                                        <Form.Item>
                                                            <Button type="link" onClick={() => addInside()} >
                                                                添加自定义时间
                                                            </Button>
                                                        </Form.Item>
                                                    </>
                                                )}
                                            </Form.List>
                                        </Col>

                                        <SelectScroll teacherScheduleList={teacherScheduleList} form={form} dispatch={dispatch} name={name} restField={restField} xqList={xqList}></SelectScroll>
                                        <Col style={{ paddingLeft: 80 }} span={24}>
                                            <SelectDate teacherScheduleList={teacherScheduleList} restField={restField} form={form} name={name} nameChange={nameChange}></SelectDate>
                                        </Col>
                                    </Row>
                                    <Form.Item
                                        {...restField}
                                        name={[name, 'id']}
                                        required
                                        rules={[
                                            {
                                                required: false,
                                                message: '请输入内容',
                                            },
                                        ]}
                                    >
                                    </Form.Item>
                                </div>
                            </Space>
                        ))}
                        <Form.Item>
                            <Button style={{ width: 180 }} type="dashed" onClick={() => add({ weekDays: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'] })} block icon={<PlusOutlined />}>
                                自定义
                            </Button>
                        </Form.Item>
                    </>
                )}
            </Form.List>
        </Col>
    </Row>
}
const Scheduling = (props) => {
    const { visible = {}, onClose, dispatch, teacherId } = props;
    const { show = false, detail = {},
    } = visible;
    const { teacherScheduleList = [] } = detail
    const [form] = Form.useForm();
    const [defaultScheduleList, setDefaultList] = useState([])
    const [xqList, setXqList] = useState([])
    const fetchSearchList = () => {
        dispatch({
            type: 'answering/fetchListSchedule',
            callback: (e) => {
                setDefaultList(e)
            }
        })
        dispatch({
            type: 'answering/fetchListCampus',
            callback: (e) => {
                setXqList(e)
            }
        })
    }
    useEffect(() => {
        fetchSearchList()
    }, [])

    const formItems = [
        {
            label: `答疑类型`,
            name: 'teachingMode',
            type: 'select',
            select: qaType_status,
            disabled: true

        },
        {
            label: `答疑周期`,
            name: 'time',
            visible: show,
            type: 'noForm',
            formItem: <WeekItem teacherScheduleList={teacherScheduleList} form={form} dispatch={dispatch} xqList={xqList} defaultScheduleList={defaultScheduleList}></WeekItem>
        },

    ];

    const modalProps = {
        title: `排班`,
        width: 800,
        visible: typeof visible === 'boolean' ? visible : show,
        zIndex: 1001,
        destroyOnClose: true,
        okText: '确认',

    };
    useEffect(() => {
        if (!show) {
            form.resetFields()
        }
    }, [show])
    const submit = () => {
        form.validateFields().then((values) => {
            const { teacherScheduleList = [], teachingMode
            } = values
            const list = teacherScheduleList.map(item => {
                const {
                    dateTime,
                    scheduleTimes = [],
                    weekDays = [],
                    id,
                    excludeDates = [],
                    campusId,
                    classroomId
                } = item
                const schedList = defaultScheduleList.reduce((o, val, index) => {
                    const { id, startTime, endTime } = val
                    if (item['schedule' + index]) {
                        return [...o, {
                            scheduleType: 'schedule',
                            scheduleId: id,
                            maxStudentAmount: item['scheduleCount' + index],
                            startTime,
                            endTime
                        }]
                    }
                    return o
                }, [])
                const payload = {
                    teachingMode,
                    weekDays: weekDays.toString(),
                    startDate: moment(dateTime[0]).format('YYYY-MM-DD'),
                    endDate: moment(dateTime[1]).format('YYYY-MM-DD'),
                    campusId,
                    classroomId,
                    scheduleTimes: [...scheduleTimes.map(item => {
                        const { dateTime, maxStudentAmount } = item
                        return {
                            startTime: dateTime[0].format('HH:mm'),
                            endTime: dateTime[1].format('HH:mm'),
                            maxStudentAmount,
                            scheduleType: 'self'
                        }
                    }), ...schedList],
                    teacherIds: teacherId,
                    excludeDates: excludeDates.toString(),
                    id
                }

                return payload
            })
            dispatch({
                type: 'answering/fakeSaveTeacherScheduleConfig',
                payload: {
                    teacherScheduleList: list
                },
                callback: (e) => {
                    onClose();
                }
            })
        });
    }

    return (
        <Modal
            {...modalProps}
            onCancel={onClose}
            onOk={() => {
                submit()
                // onClose();
            }}
        >
            <FormCondition const formItemLayouts={
                {
                    labelCol: {

                    },
                    wrapperCol: {

                    },
                }
            }
                form={form} initialValues={detail} formItems={formItems}></FormCondition>
        </Modal>
    )
}


export default connect(({ order, loading }) => ({
    loading: loading.effects['answering/fakeSaveTeacher'],
}))(Scheduling);
